<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>会话消息管理系统</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.4/socket.io.js"></script>
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }

    body { font-family: Arial, sans-serif; }

    .container {
      display: flex;
      height: 100vh;
      background: #f0f2f5;
    }

    .left-panel {
      width: 300px;
      background: white;
      border-right: 1px solid #ddd;
      display: flex;
      flex-direction: column;
    }

    .header {
      padding: 15px;
      border-bottom: 1px solid #ddd;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    /* 注释掉新建对话的按钮样式 */
    /* .btn-new {
      padding: 8px 15px;
      background: #1677ff;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    } */

    .conversation-list {
      flex: 1;
      overflow-y: auto;
    }

    .conversation-item {
      padding: 12px 15px;
      cursor: pointer;
      transition: background 0.2s;
    }

    .conversation-item:hover { background: #f5f5f5; }
    .conversation-item.active { background: #e6f4ff; }

    .right-panel {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
    }

    .message-bubble {
      max-width: 70%;
      margin: 10px 0;
      padding: 12px 16px;
      border-radius: 8px;
      position: relative;
    }

    .message-bubble.user {
      background: #1677ff;
      color: white;
      margin-left: auto;
    }

    .message-bubble.bot {
      background: #e5e3e3;
      margin-right: auto;
    }

    .timestamp {
      font-size: 0.75em;
      color: rgba(0,0,0,0.45);
      margin-top: 4px;
    }

    /* 放大图片相关样式 */
    .full-img-container {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.8);
      z-index: 1000;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }

    .full-img-container img {
      max-width: 90%;
      max-height: 90%;
    }

    .context-menu {
      position: fixed;
      background: white;
      border: 1px solid #ddd;
      box-shadow: 0 2px 8px rgba(0,0,0,0.15);
      z-index: 1000;
    }

    .menu-item {
      padding: 8px 12px;
      cursor: pointer;
      transition: background 0.2s;
    }

    .menu-item:hover { background: #f5f5f5; }
  </style>
</head>
<body>
  <div id="app">
    <div class="container">
      <div class="left-panel">
        <div class="header">
          <div><b>会话消息管理系统</b></div>
          <!-- 新建会话按钮 -->
          <!-- <button class="btn-new" @click="createConversation">新建会话</button> -->
        </div>
        <div class="conversation-list">
          <div v-for="conv in conversations"
               :key="conv.id"
               :class="['conversation-item', { active: selectedConv?.id === conv.id }]"
               @click="selectConversation(conv)"
               @contextmenu.prevent="showMenu($event, conv)">
            {{ conv.name }}
          </div>
        </div>
      </div>

      <div class="right-panel">
        <div v-for="msg in messages"
             :key="msg.id"
             :class="['message-bubble', msg.sender]">
          <template v-if="msg.type === 'text'">
            {{ msg.content }}
          </template>
          <template v-else-if="msg.type === 'image'">
            <img 
              :src="'data:image/jpeg;base64,' + msg.content" 
              style="max-width: 200px;" 
              @click="showFullImage(msg.content)"
            >
          </template>
          <div class="timestamp">{{ formatTime(msg.timestamp) }}</div>
        </div>

        <!-- 放大图片的容器 -->
        <div v-if="showFullImg" class="full-img-container">
          <img 
            :src="'data:image/jpeg;base64,' + currentImg" 
            @click="closeFullImage"
          >
        </div>
      </div>

      <div v-if="menu.visible" 
           class="context-menu"
           :style="{ left: menu.x + 'px', top: menu.y + 'px' }">
        <div class="menu-item" @click="renameConversation">重命名</div>
        <div class="menu-item" @click="deleteConversation">删除</div>
      </div>
    </div>
  </div>

  <script>
    new Vue({
      el: '#app',
      data: {
        conversations: [],
        selectedConv: null,
        messages: [],
        menu: { visible: false, x: 0, y: 0, target: null },
        showFullImg: false,
        currentImg: null
      },
      mounted() {
        this.loadConversations();
        const socket = io('http://localhost:3000');
        socket.on('conversation_update', () => this.loadConversations());

        // 添加键盘事件监听
        window.addEventListener('keyup', this.handleKeyboardEvent);
      },
      beforeDestroy() {
        // 移除键盘事件监听
        window.removeEventListener('keyup', this.handleKeyboardEvent);
      },
      methods: {
        loadConversations() {
          fetch('/api/conversations')
            .then(res => res.json())
            .then(data => {
              this.conversations = data;
              if (this.conversations.length > 0 && !this.selectedConv) {
                this.selectConversation(this.conversations[0]);
              }
            });
        },
        selectConversation(conv) {
          this.selectedConv = conv;
          fetch(`/api/messages?conversation_id=${conv.id}`)
            .then(res => res.json())
            .then(data => this.messages = data);
        },
        showMenu(e, conv) {
          this.menu = {
            visible: true,
            x: e.pageX,
            y: e.pageY,
            target: conv
          };
          document.addEventListener('click', this.closeMenu);
        },
        closeMenu() {
          this.menu.visible = false;
          document.removeEventListener('click', this.closeMenu);
        },
        renameConversation() {
          const newName = prompt('新名称', this.menu.target.name);
          if (newName) {
            fetch(`/api/conversations/${this.menu.target.id}`, {
              method: 'PUT',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ name: newName })
            });
          }
          this.closeMenu();
        },
        deleteConversation() {
          if (confirm('确定删除该会话吗？')) {
            fetch(`/api/conversations/${this.menu.target.id}`, {
              method: 'DELETE'
            })
              .then(() => {
                this.selectedConv = null;
                this.messages = [];
                this.loadConversations();
              });
          }
          this.closeMenu();
        },
        formatTime(timestamp) {
          const date = new Date(timestamp);
          return `${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
        },
        showFullImage(imgSrc) {
          this.currentImg = imgSrc;
          this.showFullImg = true;
        },
        closeFullImage() {
          this.showFullImg = false;
        },
        handleKeyboardEvent(event) {
          if (event.key === 'Escape') {
            this.closeFullImage();
          }
        }
      }
    });
  </script>
</body>
</html>